from fastapi import APIRouter, File, UploadFile
from typing import List
import os

file_router = APIRouter()


# 上传单个文件
@file_router.post("/upload_file")
async def upload_file(file: bytes = File()):
    # 适合小文件上传，因为这里用的是用户内存
    # 所以这种方式并不常用
    print("file", file)
    return {"file_size": len(file)}


# 上传多个文件
@file_router.post("/upload_files")
async def upload_files(files: List[bytes] = File()):
    for file in files:
        print("file_length", len(file))
    return {
        "data": len(files)
    }


# 使用文件句柄
# 上传一个文件
@file_router.post("/upload_file_handler")
async def upload_file_handler(file: UploadFile = File()):
    print("file:", file)
    path = os.path.join("assets", "imgs", file.filename)
    print("path:", path)
    with open(path, "wb") as f:
        for line in file.file:
            f.write(line)

    return {
        "data": {
            "filename": file.filename
        }
    }


# 上传多个文件
@file_router.post("/upload_multi_file_handler")
async def upload_multi_file_handler(files: List[UploadFile] = File()):
    for file in files:
        print("file", file)
        path = os.path.join("assets", "imgs", file.filename)
        print("path:", path)
        with open(path, "wb") as f:
            for line in file.file:
                f.write(line)
    return {
        "code": 200,
        "message": "上传文件成功！"
    }
